<?php  
/*
 

// FirePHP [http://www.firephp.org/HQ/Use.htm]
$this->firephp->log($var, 'my var');

*/
// defined('MODUL') ||
//  define('MODUL','People');
 

//require_once $_SERVER['DOCUMENT_ROOT']."/Moduls/".MODUL."/".MODUL.".php"; 
//require_once $_SERVER['DOCUMENT_ROOT']."/Moduls/".MODUL."/view.".MODUL.".php"; 
 
 
 
class PeopleModul extends BasicModulController implements BasicModulControllerInterface {
 
 
    function __construct($registry = null){
      
      parent::__construct();
      
      $this->registry = $registry; 
      
      if($this->getURIarg(1)){
        //echo $this->getURIarg(1);
      }
      
      
      // die(var_dump($this->action));
        
      //var_dump($this->action);
      if(isset($this->registry) AND ($this->registry->get('virtual_modul_index')) != '')
         $this->life_modul_index = $this->registry->get('virtual_modul_index'); 
      elseif(isset($this->registry) AND ($this->registry->get('modul_index')) != '')   
        $this->life_modul_index = $this->registry->get('modul_index'); 
       
      // $this->life_modul_index // 'about' 
      $this->modul_index = $this->registry->get('modul_index'); // 'People'
       
      // Widgets 
      $this->widget_enter_data = array();
      $this->widget_enter_data['widget'] = array('1'=>'a'); //var_dump($this->widget_enter_data);
      
      // Model
      $this->model = new People;  
      
      // View
      $class_name = $this->modul_index . "View";
      
      $ModulView = new $class_name;  
      $this->global_view = $ModulView->getView();  
      $this->view = $ModulView;  
      
      // setting vars from model
      //$this->view->Set('asd',1234);
      
      self::$instance = $this;
      
      // generate html       
      //$this->html = $this->view->render();
      
   
      //$left_menu = $this->view->Get('inc_navigator.tpl');
      $left_menu = '';
      //$this->global_view->Set('left_menu',$left_menu); 
      
      $this->sections_arr = $this->getSections();  
      
      if(is_array($this->sections_arr))
        $this->view->Set('sections',$this->sections_arr);
      else   
        $this->view->Set('sections',null);
      
      $left_menu = $this->view->Get('inc_navigator.tpl');
       
      $this->global_view->Set('left_menu',$left_menu);
      
    } // -- __construct
    
    
    function getHtml(){
        return $this->html;
    }
    
    
    
    
    
    
    public static function getInstance(){
    // [!] method is must
        if (!isset(self::$instance)) {
            $className = __CLASS__;
            self::$instance = new $className;
        }

        return self::$instance;
    } // --
    
    static function action(){
        //die(var_dump(__CLASS__));
        $obj = static::getInstance();
         
        $method = $obj->action;
        $obj->$method();  
        
        //die(var_dump($obj->action));
    } // --
    
    static function router($section_id){
         
        $modul = static::getInstance();
        
        switch($section_id){
            case 805: $modul->showPeople();
            break;
            
            default:
            break;
        }
    } // --
    
 
   
    // -------- Actions ----------
    
    //function actionPeopleAsd()
    
    
    function actionPeopleBasic(){  
    // action по умолчанию
    // точка входа
        $this->showPeople();
        //$this->html =  $this->view->render();
        
    } // --
    
    function showPeople(){  
    // вывод достижений учеников
      
        $action = 'dostigeniya';
        $this-> view->Set('action',$action); 
        $this->  global_view->Set('navhigh',$action); 
    
        if($this->getURIarg(2) == 'edit' AND User::isAdmin())
        // управление разделом - вызов метода либо редирект на другую точку входа
          
          header("Location:/people/edit"); // TODO заменить ptople на константу
        else {
          //$this-> view->Set('action','Basic');
          
          $people = $this->model->getPeople();  
          
          if(is_array($people )){
            $this-> view->Set('people',$people);
          }
        
          $this->html =  $this->view->render();
        }  
        
    } // --
    
    function actionPeopleEdit(){ 
    // точка входа
        
        if(!User::isAdmin()) return null;  
          
        $this-> view->Set('submitButtonName','Создать'); 
        $action = 'dostigeniya';
        $this-> view->Set('action',$action); 
        $this->  global_view->Set('navhigh',$action); 
        
        //$this->addJs('upload_files_ajax.js', $get_script_from_standard_dir = true); 
        //$this->addJs('jquery.form.js', $get_script_from_standard_dir = true); 
        //$this->addJs('jquery.blockUI.js', $get_script_from_standard_dir = true); 
        
        $people = false;
        $people = $this->model->getPeople();
        $this-> view->Set('people',$people); //fb($people);
        $this-> view->Set('update_people_form_action','/'.MODUL_INDEX.'/UpdatePeople'); 
         
        
        $this->html =  $this->view->render('editPeople.tpl');
    
    } // --
    
    function addPupil(){
    // точка входа
    
        if(!User::isAdmin()) return null;  
        if(!isset($_POST['pupil'])) return null;   
        
        
        //TODO валидация
        //TODO move to model
        //TODO сделать с тумбнаилкой
        $pupil = $_POST['pupil'];
        
              
        
        //var_dump($_FILES['photo']['name'][0]);
        $condition = '';
        $photo = " `photo` =   ";
        $mess = '';
        
        foreach($pupil as $option => $value){
        // name   surname     small_info info extra_info
            $condition .= " $option = '$value', "; 
        }
         
       
       
       if(isset($_FILES['photo']['name'])){
       // name type tmp_name error size
          $c = count($_FILES['photo']['name']);
          $photo .= "'";
          
          for($i=0; $i<$c; $i++){
              $old_name = $_FILES['photo']['tmp_name'][$i];
              $new_name = md5($old_name . date("m.d.y")) . ".jpg";
              $photo .=  $new_name ;
              if(($i+1) < $c) $photo .= ";";
              
              $path = $_SERVER['DOCUMENT_ROOT'] . "../Image/people/$new_name";
              
              $res = $this->model->imgCropAndResize($old_name, $path, 300);
              
              /*
              пример
              $tmb = "sm_" . $img_name. ".jpg";
              $big = $img_name. ".jpg";
              
              $photo .=  $img_name ; 
              
              $path_1 = $_SERVER['DOCUMENT_ROOT'] . "../Image/news/$tmb";
              $path_2 = $_SERVER['DOCUMENT_ROOT'] . "../Image/news/$big";
              
              $res_1 = $this->imgCropAndResize($old_name, $path_1, 300);
              $res_2 = $this->imgCropAndResize($old_name, $path_2, 600);
              */
              
              if($res == -100) $mess = 'картинку нужно уменьшить';
          }
          $photo .= "'";
          
       } else $photo .= "' '"; 
         
      $q = "INSERT INTO `people` SET  $condition $photo, refresh_date	= '" . date("Y-m-d") . "'"; 
       $r = mysql_query($q);
       if(!$r) return -1;
       
       header("Location:/".MODUL."/edit");
    
    }// --
    
    function actionPeopleUpdatePeople(){
    // точка входа
    
    //TODO валидация
    //TODO move to model
    
        if(!User::isAdmin()) return null;
        if(!isset($_POST)) return null;
        
         
        foreach($_POST['people'] as $people_id => $value){       

            if(isset($value['delete'])){
              $q = "DELETE FROM `people` WHERE people_id = {$value['people_id']}";
              $r = mysql_query($q);
            } else {
            
              $name = $value['name'];
              $surname = $value['surname'];
              $small_info = $value['small_info'];
              $info = $value['info'];
              $extra_info = $value['extra_info'];
              //$value['seolink'];
              //$value['video']; 
              
               
              
              
              $q = "UPDATE `people` SET `name` = '$name', 
                                          `surname` = '$surname', 
                                          `small_info` = '$small_info',
                                          `info` = '$info',
                                          `extra_info` = '$extra_info'
                    WHERE people_id = {$value['people_id']}  ";
              $r = mysql_query($q);
              
              
               
            }
            
            
        }    
        header("Location:/".MODUL."/edit");
    
    } // --
    
    
    
    
    
    
    
    
    
    
}

    
 
?>